﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.DynamicProxy;
using System.ComponentModel;
using NUnit.Framework;
using EasyProp;

namespace EasyProp.Tests
{
    [TestFixture]
    public class DoNothingIfValueNotChangedFixture
    {
        [SetUp]
        public void SetUp()
        {
            _easyPropBuilder = new EasyPropBuilder();
        }

        [Test]
        public void cancels_execution_if_value_not_changed()
        {
            ClassWithDoNothingIfNotChangedAttribute theObject = _easyPropBuilder.Build<ClassWithDoNothingIfNotChangedAttribute>();

            bool gotEvent = false;          
            theObject.Changed += delegate(object sender, EventArgs e)
            {
                gotEvent = true;
            };

            theObject.MyProperty = "hello";
            Assert.IsTrue(gotEvent, "We should get the event the first time");
            gotEvent = false;
            theObject.MyProperty = "hello";
            Assert.IsFalse(gotEvent, "No change in value, we should not get event");
        }

        [Test]
        public void invokes_other_filters_if_value_changed()
        {
            ClassWithBeforeAndAfterFilter theObject = _easyPropBuilder.Build<ClassWithBeforeAndAfterFilter>();

            CountInvocationsFilter.Count = 0;
            theObject.MyProperty = "hello";
            CountInvocationsFilter.Count = 1;
        }

        EasyPropBuilder _easyPropBuilder;

        [BeforePropertySetFilter(typeof(DoNothingIfValueNotChanged))]
        public class ClassWithDoNothingIfNotChangedAttribute
        {
            public event EventHandler Changed;

            public virtual string MyProperty
            {
                get { return _myProperty; }
                set
                {
                    _myProperty = value;
                    OnChanged();
                }
            }

            private void OnChanged()
            {
                if (this.Changed != null)
                {
                    this.Changed(this, EventArgs.Empty);
                }
            }

            string _myProperty;
        }

        [BeforePropertySetFilter(typeof(DoNothingIfValueNotChanged))]
        [AfterPropertySetFilter(typeof(CountInvocationsFilter))]
        public class ClassWithBeforeAndAfterFilter
        {
            public virtual string MyProperty { get; set; }
        }


    }
}
